#include <gtkmm.h>
#include <iostream>
#include <string>
#include "dbpage.h"

using namespace std;

//extern char binary_glade_start[];

Gtk::Window* window = 0;
Gtk::TreeView* treeview = 0;
Glib::RefPtr<Gtk::ListStore> model;
Gtk::Entry* searchEntry =0;
Gtk::Label* lblResults = 0;
Gtk::MenuItem* quitMenuItem = 0;
Gtk::ToolButton* tbGoFirst = 0;
Gtk::ToolButton* tbGoPrevious = 0;
Gtk::ToolButton* tbGoNext = 0;
Gtk::ToolButton* tbGoLast = 0;
Gtk::Toolbar* toolBar = 0;
DbPage* db;

class ModelColumns : public Gtk::TreeModelColumnRecord {
public:
    ModelColumns() {
        add(icon);
        add(number);
        add(date);
        add(customer);
        add(phone);
        add(ip);
        add(status);
        add(active);

    }
    Gtk::TreeModelColumn< Glib::RefPtr<Gdk::Pixbuf> >  icon;
    Gtk::TreeModelColumn<string> number;
    Gtk::TreeModelColumn<string> date;
    Gtk::TreeModelColumn<string> customer;
    Gtk::TreeModelColumn<string> phone;
    Gtk::TreeModelColumn<string> ip;
    Gtk::TreeModelColumn<string> status;
    Gtk::TreeModelColumn<string> active;

};


string pad_left(string& text, int count)
{
    for(int i=0; i<count; i++)
        text.insert(i,"0");
    return text.substr(text.length()-count, count);

}
string number2String(int number)
{
    stringstream out;
    out << number;
    return  out.str();

}
static void on_button_quit_clicked() {
    if (window)
        window->hide();
}

Glib::RefPtr<Gdk::Pixbuf> get_icon(string status) {
    Glib::RefPtr<Gdk::Pixbuf> icon = Gdk::Pixbuf::create_from_file("images/gray.png");
    if (status == "open")
        icon = Gdk::Pixbuf::create_from_file("images/red.png");
    if (status == "working")
        icon = Gdk::Pixbuf::create_from_file("images/yellow.png");
    if (status == "waiting")
        icon = Gdk::Pixbuf::create_from_file("images/green.png");
    return icon;
}

void on_treeview_column_clicked() {
    cout << "column 1 clicked" << endl;
}


void on_treeview_row_activated(const Gtk::TreeModel::Path& path,
                               Gtk::TreeViewColumn* column) {
    Gtk::TreeModel::iterator iter = model->get_iter(path);
    if (iter) {
        Gtk::TreeModel::Row row = *iter;
        //cout << "Row activated: " << row[columns.status] << endl;
        cout <<  "Column: "<<column->get_title() << endl;
    }
}
void set_results()
{
    tbGoFirst->set_sensitive(db->firstOk());
    tbGoPrevious->set_sensitive(db->previousOk());
    tbGoNext->set_sensitive(db->nextOk());
    tbGoLast->set_sensitive(db->lastOk());

    string results = "    " + number2String(db->first) + "-"+
        number2String(db->last) +
        "/" + number2String(db->total) +"   ";
    lblResults->set_text(results);
    if(db->last==0)
         lblResults->set_text("No results");
    if (searchEntry->get_text() != "")
        lblResults->set_text(lblResults->get_text()+" (Filtered)");


    //statusBar1->showMessage(QString::number(time.elapsed()));
}

void load_model(vector< vector<string> >* table) {
    model->clear();
    if(table){
    for (vector<string>::size_type i = 0; i != table->size(); i++) {
        Gtk::TreeModel::Row row = *(model->append());
        row.set_value(0, get_icon(table->at(i).at(5)));
        string value = "";
        for (unsigned int j = 0; j < table->at(i).size(); j++) {
            value = table->at(i).at(j);
            switch (j) {
            case 0: // zero-padd number column
                value = pad_left(value,6);
                break;
            case 6: // replace 0,1 by YES or NO in active column
                value = (value=="1")?"YES":"NO";
                break;
            }
            row.set_value(j+1, value);
        }
    }
    set_results();
    }

}

bool on_key_press_event(GdkEventKey* event) {
	if (event->keyval == GDK_Return)
		load_model(db->search(searchEntry->get_text(),1,"number asc"));
	return false;
}
static void on_first_clicked() {
    load_model(db->search(searchEntry->get_text(),1,"number asc"));
}
static void on_previous_clicked() {
    load_model(db->search(searchEntry->get_text(),db->previousPage(),"number asc"));
    cout << "previous click" << db->previous << endl;
}
static void on_next_clicked() {
    load_model(db->search(searchEntry->get_text(),db->nextPage(),"number asc"));
}
static void on_last_clicked() {
    load_model(db->search(searchEntry->get_text(),db->lastPage(),"number asc"));
}


int main (int argc, char **argv) {

    Gtk::Main kit(argc, argv);
    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create();

    try {
        builder->add_from_file("glade.ui");
    } catch (const Glib::FileError& ex) {
        cerr << "FileError: " << ex.what() << endl;
    } catch (const Gtk::BuilderError& ex) {
        cerr << "BuilderError: " << ex.what() << endl;
    }
    //cout << "ok here"<< endl;
    // setup UI
    builder->get_widget("window1", window);
    builder->get_widget("tbQuit", quitMenuItem);
    quitMenuItem->signal_activate().connect( sigc::ptr_fun(on_button_quit_clicked) );

    builder->get_widget("searchEntry", searchEntry);
    // very important: add false param to catch the signal
    searchEntry->signal_key_press_event().connect( sigc::ptr_fun(on_key_press_event),false );

    builder->get_widget("treeview1", treeview);
    builder->get_widget("lblResults", lblResults);

    builder->get_widget("tbGoFirst", tbGoFirst);
    tbGoFirst->signal_clicked().connect( sigc::ptr_fun(on_first_clicked) );
    builder->get_widget("tbGoPrevious", tbGoPrevious);
    tbGoPrevious->signal_clicked().connect( sigc::ptr_fun(on_previous_clicked) );
    builder->get_widget("tbGoNext", tbGoNext);
    tbGoNext->signal_clicked().connect( sigc::ptr_fun(on_next_clicked) );
    builder->get_widget("tbGoLast", tbGoLast);
    tbGoLast->signal_clicked().connect( sigc::ptr_fun(on_last_clicked) );

    //builder->get_widget("toolBar", toolBar);

    // Tree model:
    ModelColumns columns;
    model = Gtk::ListStore::create(columns);
    treeview->set_model(model);
    treeview->signal_row_activated().connect(sigc::ptr_fun(&on_treeview_row_activated));

    //Fill the TreeView's model
    db = new DbPage;
    load_model(db->search("",1,"number asc"));

    treeview->append_column("", columns.icon);
    treeview->append_column("number", columns.number);
    treeview->append_column("date", columns.date);
    treeview->append_column("customer", columns.customer);
    treeview->append_column("phone", columns.phone);
    treeview->append_column("ip", columns.ip);
    treeview->append_column("status", columns.status);
    treeview->append_column("active", columns.active);

    for (guint i = 0; i < treeview->get_columns().size(); i++) {
        Gtk::TreeView::Column* pColumn = treeview->get_column(i);
        //pColumn->set_clickable(true);
        pColumn->set_resizable(true);
        //pColumn->set_reorderable(true);
        //pColumn->set_sort_indicator(true);
        //pColumn->set_sort_column(columns.number);
    }
    //treeview->set_headers_clickable	();
    treeview->get_column(1)->set_sort_column(columns.number);
    //treeview->get_column(1)->signal_clicked().connect(
    //sigc::ptr_fun(&on_treeview_column_clicked) );

    kit.run(*window);
    return 0;
}
//}
